import os
import requests
import zipfile
from io import BytesIO

from constants import OUTPUT_FOLDER


def file_name_edge(filename, end_logo_list):
    for end_logo in end_logo_list:
        if filename.endswith(end_logo):
            return True
    return False


def clone_file(link, end_logo_list, output_folder=OUTPUT_FOLDER):
    try:
        # 下载压缩文件
        response = requests.get(link)
        response.raise_for_status()  # 检查请求是否成功

        # 读取 zip 文件内容
        with zipfile.ZipFile(BytesIO(response.content)) as zip_file:
            # 遍历压缩文件中的所有文件
            for file_info in zip_file.infolist():
                if file_name_edge(file_info.filename, end_logo_list) and 35840 > file_info.file_size > 4096:
                    # 解压缩并保存符合条件的文件
                    extracted_path = zip_file.extract(file_info, output_folder)
                    # print(f"解压并过滤文件: {extracted_path}, 文件大小: {file_info.file_size} 字节")
        return 0

    except requests.exceptions.RequestException as e:
        print(f"下载失败: {link}, 错误信息: {e}")
        return link
    except zipfile.BadZipFile:
        print(f"无效的压缩文件: {link}")
        return link

if __name__ == '__main__':
    clone_file('https://github.com/public-apis/public-apis/archive/refs/heads/master.zip', OUTPUT_FOLDER)